package com.lw.leetcode.str.b;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * 1156. 单字符重复子串的最大长度
 *
 * @author liw
 * @version 1.0
 * @date 2022/4/5 19:18
 */
public class MaxRepOpt1 {

    public static void main(String[] args) {
        MaxRepOpt1 test = new MaxRepOpt1();

        // 3
//        String str = "ababa";

        // 3
//        String str = "aabba";

        // 4
        String str = "bbaaaabbccbb";

        int i = test.maxRepOpt1(str);
        System.out.println(i);
    }

    public int maxRepOpt1(String text) {
        char[] chars = text.toCharArray();
        List<Integer> ilist = new ArrayList<>();
        List<Character> clist = new ArrayList<>();
        int[] arr = new int[26];
        int length = chars.length;
        int count = 1;
        for (int i = 1; i < length; i++) {
            if (chars[i] == chars[i - 1]) {
                count++;
            } else {
                clist.add(chars[i - 1]);
                ilist.add(count);
                count = 1;
                arr[chars[i - 1] - 'a']++;
            }
        }
        clist.add(chars[length - 1]);
        ilist.add(count);
        arr[chars[length - 1] - 'a']++;
        int size = clist.size();
        int max = ilist.get(0);
        if ( arr[chars[0] - 'a'] > 1) {
            max++;
        }
        if (size > 1) {
            if ( arr[clist.get(1) - 'a'] > 1) {
                max = Math.max(max, ilist.get(1) + 1);
            } else {
                max = Math.max(max, ilist.get(1));
            }
        }
        for (int i = 2; i < size; i++) {
            int n = arr[clist.get(i) - 'a'];
            if (n == 1) {
                max = Math.max(max, ilist.get(i));
            } else if (n == 2) {
                if (ilist.get(i - 1) == 1 && clist.get(i - 2).equals(clist.get(i))) {
                    max = Math.max(max, ilist.get(i) + ilist.get(i - 2));
                } else {
                    max = Math.max(max, ilist.get(i) + 1);
                }
            } else if (n > 2) {
                if (ilist.get(i - 1) == 1 && clist.get(i - 2).equals(clist.get(i))) {
                    max = Math.max(max, ilist.get(i) + ilist.get(i - 2) + 1);
                } else {
                    max = Math.max(max, ilist.get(i) + 1);
                }
            }
        }
        return max;
    }

}
